﻿namespace HareGame
{
    public class PoolObj : MonoBehaviour_Ex
    {
        public string PoolName;

        /// <summary>
        /// 预加载时触发
        /// </summary>
        public virtual void OnPreload()
        {
            gameObject.SetActive(false);
        }

        /// <summary>
        /// 对象创建时触发
        /// </summary>
        /// <param name="poolName">对象池名字</param>
        public virtual void OnCreate(string poolName)
        {
            PoolName = poolName;
        }

        /// <summary>
        /// 对象回收时触发
        /// </summary>
        public virtual void OnRecycle()
        {
        
        }

        /// <summary>
        /// 回收自己
        /// </summary>
        /// <param name="includeChild">是否回收子节点下的对象</param>
        public virtual void RecycleSelf(bool includeChild = false)
        {
            GameEntry.Pool.Recycle(PoolName, this);
            if (includeChild)
            {
                RecycleChilds();
            }
        }

        /// <summary>
        /// 回收所有子节点对象
        /// </summary>
        protected void RecycleChilds()
        {
            PoolObj[] allObj = GetComponentsInChildren<PoolObj>();
            foreach (var obj in allObj)
            {
                if (obj != this)
                {
                    GameEntry.Pool.Recycle(obj.PoolName, obj);
                }
            }
        }
    }
}
